//上报
import config from "./config";
import { generateUniqueId } from "./utils";
import { addCache, getCache, clearCache } from "./cache";
export const originalProto = XMLHttpRequest.prototype;
export const originalOpen=XMLHttpRequest.prototype.open;
export const originalSend=XMLHttpRequest.prototype.send;

export function isSupportSendBeacon(){
  return 'sendBeacon' in navigator;
}

export function report(data:any) { 
    if(!config.url){
        console.error("请设置上传地址")
        return
    }
    const reportData=JSON.stringify({
        id:generateUniqueId(),
        data
    })

    //上传数据，使用图片的方式
    if(config.isImageUpload){
        imgRequest(reportData);
    }else{
        //判断是否支持sendBeacon，若支持，使用sendBeacon
        if(isSupportSendBeacon()){
            return beaconRequest(reportData);
        }else{
            //使用原生xhr 发送数据
            xhrRequest(reportData)
        }
    }
}

//批量上传报告
export function lazyReportBatch(data:any){
    addCache(data);
    const dataCache=getCache();
     if(dataCache.length&&dataCache.length>=config.batchSize){
        report(dataCache);
        clearCache();
    }
}


//图片发送数据
export function imgRequest(data:any){
    const img=new Image();
    img.src=`${config.url}?data=${encodeURIComponent(JSON.stringify(data))}`
}

//普通ajax发送请求数据（空闲时）
export function xhrRequest(data:any){
    if(window.requestIdleCallback){
        window.requestIdleCallback(
            ()=>{
                const xhr=new XMLHttpRequest();
                originalOpen.call(xhr,'POST',config.url,true);
                originalSend.call(xhr,JSON.stringify(data));
            },
            { timeout: 3000 }
        )
    }else{
         setTimeout(()=>{
            const xhr=new XMLHttpRequest();
            originalOpen.call(xhr,'POST',config.url,true);
            originalSend.call(xhr,JSON.stringify(data));
        })
    }

}

export function beaconRequest(data:any) :void{ 
    if(window.requestIdleCallback){
        window.requestIdleCallback(
            ()=>{
                window.navigator.sendBeacon(config.url,data);
            },
            {timeout:3000}
        )
    }else{
        setTimeout(()=>{
            window.navigator.sendBeacon(config.url,data);
        })
    }
}